import axios from 'axios';
import jsonBig from 'json-bigint';
const contentType = 'application/json;charset=UTF-8';
var base = 'api';
// var base = 'http://192.168.10.233:19980';
const JSONbigToString = jsonBig({ storeAsString: true });
const request =axios.create({
    baseURL: base,
    headers: {
		'Content-Type': contentType
	},
    transformResponse: [
		function (data) {
			try {
				// console.log(JSONbigToString.parse(data));
				return JSONbigToString.parse(data);
			} catch (err) {
				return data;
			}

		}
	]
})
request.defaults.headers['Access-Control-Allow-Origin'] = "*";
request.defaults.headers['Access-Control-Allow-Methods'] = "GET,PUT,POST,DELETE,OPTIONS";
request.interceptors.request.use(
	config => {
		const token = localStorage.getItem('token');
		if (!token && config.url == '/login/login') {
			return config;
		} else {
			config.headers['token'] = token;
			
			return config;
		}
	},
	error => {
		return Promise.reject(error)
	}
)

const errorHandle = (status, other) => {
	switch (status) {
		case 400:
            console.log('信息校验失败');
			break
		case 401:
			// @ts-nocheck
			console.log('认证失败');
			// router.replace({
			// 	name:'login'
			// })
			ElMessage({
				type: "warning",
				message: "登录过期,请重新登陆!",
			});
			break
		case 403:
			console.log('token校验失败');
			// router.replace({
			// 	name:'login'
			// })
			ElMessage({
				type: "warning",
				message: "登录过期,请重新登陆!",
			});
			break
		case 404:
            console.log('请求的资源不存在');
			break
		default:
			break
	}
}

request.interceptors.response.use(
	// 响应包含以下信息data,status,statusText,headers,config
	res => {
		if (res.data && res.data.code !== 0 && !(res.data instanceof Blob)) {
            // console.log(res.data.message || '服务器出错!');
		}
		// 请求通用处理
		errorHandle(res.data.code, res.data)
		return res.data
	},
	err => {
		// console.log(err);
		const { response } = err
		if (response) {
			errorHandle(response.status, response.data)
			return Promise.reject(response)
		}
        // console.log('请求失败');
		return response
	}
)
export default request;